package cn.kgc.shiro03.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/7/28
 * @Description:  shiro的配置类
 */
@Configuration
public class ShiroConfig {

    // shirode过滤器配置
    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 配置拦截 规则
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        // 设置放行资源  路径  anon -> AnonymousFilter  指定的路径可以匿名访问
        map.put("/user/login","anon");
        map.put("/user/register","anon");
        // 放行验证码请求
        map.put("/captcha/getCode","anon");
        // 放行静态资源
        map.put("/register.html","anon");
        map.put("/css/*.css","anon");
        map.put("/js/*.js","anon");
        map.put("/font/**","anon");
        // authc shiro过滤器的简写   FormAuthenticationFilter
        map.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        // 设置拦截请求后跳转的路径
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        return shiroFilterFactoryBean;
    }


    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm customerRealm){

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(customerRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    public CustomerRealm customerRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("MD5");
        hashedCredentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return customerRealm;
    }
}
